using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Fieldbook.Business
{
    public static class JSONSerializator<T>
    {
        public static string ListToJson(List<T> listInstances)
        {
            StringBuilder sb = new StringBuilder();
            PropertyInfo[] properties = typeof(T).GetProperties();
            for (int i = 0; i < listInstances.Count; i++)
            {
                if (i != 0) sb.AppendLine(",");
                sb.Append("{");
                T instance = listInstances[i];
                for (int j = 0; j < properties.Length; j++)
                {
                    if (j != 0) sb.Append(",");
                    PropertyInfo pi = properties[j];
                    object value = pi.GetValue(instance, null);
                    if (value != null && pi.PropertyType == typeof(Fieldbook.Entities.Field.FieldState?))
                    {
                        value = (byte)value;
                    }
                    sb.AppendFormat("{0}: '{1}'", pi.Name, value);
                }
                sb.Append("}");
            }
            return sb.ToString();
        }

        public static string ListToJson(List<T> listInstances, params string[] properties)
        {
            StringBuilder sb = new StringBuilder();
            PropertyInfo[] allProperties = typeof(T).GetProperties();
            List<PropertyInfo> propertiesList = new List<PropertyInfo>();
            propertiesList.AddRange(allProperties);
            for (int i = 0; i < listInstances.Count; i++)
            {
                if (i != 0) sb.AppendLine(",");
                sb.Append("{");
                T instance = listInstances[i];
                for (int j = 0; j < properties.Length; j++)
                {
                    PropertyInfo pi = propertiesList.Find(delegate(PropertyInfo pInfo) { return pInfo.Name == properties[j]; });
                    if (pi != null)
                    {
                        if (j != 0) sb.Append(",");
                        object value = pi.GetValue(instance, null);
                        if (value != null && pi.PropertyType == typeof(Fieldbook.Entities.Field.FieldState?))
                        {
                            value = (byte)value;
                        }
                        if (value != null && pi.PropertyType == typeof(Fieldbook.Entities.PlantSpecie.PlantCategory?))
                        {
                            value = (int)value;
                        }
                        sb.AppendFormat("{0}: '{1}'", pi.Name, value);
                    }
                }
                sb.Append("}");
            }
            return sb.ToString();
        }
    }
}
